package com.example.statistics.weight

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.GridLayoutManager
import com.example.statistics.R
import com.example.statistics.ex.messageDialog
import com.jhj.httplibrary.HttpCall
import com.jhj.imageselector.bean.LocalMedia
import com.jhj.imageselector.weight.GridSpacingItemDecoration
import com.jhj.slimadapter.SlimAdapter
import com.example.statistics.ex.glide
import com.example.statistics.ex.imageDisplay
import com.example.statistics.ex.imageSelected
import kotlinx.android.synthetic.main.grid_view_image.view.*
import org.jetbrains.anko.dip
import org.jetbrains.anko.sdk27.coroutines.onClick

class ImageLayout : LinearLayout {
    companion object {
        const val IMAGE_DISPLAY = 0
        const val IMAGE_SELECTOR = 1
        const val IMAGE_DISPLAY_TITLE = 2
    }

    private var imageSelector: (List<LocalMedia>?) -> Unit = {}
    private var imageDelete: (String) -> Unit = {}

    private val mView: View

    //样式
    private var imageStyle = IMAGE_DISPLAY

    //图片列表
    private val adapter = SlimAdapter.creator()

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {

        mView = LayoutInflater.from(context).inflate(R.layout.grid_view_image, this, false)
        val typedArray = context?.obtainStyledAttributes(attrs, R.styleable.ImageLayout)
        imageStyle = typedArray?.getInt(R.styleable.ImageLayout_image_style, imageStyle)
                ?: imageStyle

        typedArray?.recycle()
        initView(mView)
        addView(mView)
    }

    fun imageList(): MutableList<String> {
        return adapter.getDataList<String>().toMutableList()
    }

    fun localFileList(): MutableList<String> {
        return adapter.getDataList<String>().filter { it.startsWith("/storage/emulated/") }.toMutableList()
    }

    fun netFileList(): MutableList<String> {
        val list = mutableListOf<String>()
        adapter.getDataList<String>().forEach {
            if (!it.startsWith("/storage/emulated/")) {
                val str = it.replace("${HttpCall.baseUrl.orEmpty()}/upload", "")
                list.add(str)
            }
        }
        return list
    }

    fun imageSelector(body: (List<LocalMedia>?) -> Unit) {
        this.imageSelector = body
    }

    fun imageDelete(body: (String) -> Unit) {
        this.imageDelete = body
    }

    fun setImageList(list: List<String>?) {
        val resultList = mutableListOf<Any>()
        resultList.addAll(list.orEmpty().toMutableList())
        when (imageStyle) {
            IMAGE_DISPLAY -> {

            }
            IMAGE_SELECTOR -> {
                resultList.add(1)
            }
            IMAGE_DISPLAY_TITLE -> {

            }
        }
        adapter.setDataList(resultList)
    }


    private fun initView(mView: View) {
        val list = mutableListOf<Any>()
        when (imageStyle) {
            IMAGE_DISPLAY -> {

            }
            IMAGE_SELECTOR -> {
                list.add(1)
            }
            IMAGE_DISPLAY_TITLE -> {

            }
        }

        val decoration = GridSpacingItemDecoration(3, (dip(5)).toInt(), false)
        val recyclerView = mView.recycler_view_photo
        recyclerView.addItemDecoration(decoration)
        recyclerView.layoutManager = GridLayoutManager(context, 3)

        adapter.register<String>(R.layout.layout_image_selector_grid) { injector, bean, position ->
            injector
                    .with<ImageView>(R.id.iv_image_selector_picture) {
                        it.glide(bean)
                        it.onClick {
                            (context as Activity).imageDisplay(adapter.getDataList<String>().orEmpty(), position)
                        }
                    }
                    .with<ImageView>(R.id.iv_image_selector_state) {
                        if (imageStyle == IMAGE_SELECTOR) it.glide(R.drawable.ic_delete)
                        it.onClick {
                            context.messageDialog(msg = "是否删除该图片？") { alertFragment, view ->
                                val path = adapter.getDataList<String>()[position]
                                imageDelete.invoke(path)
                                adapter.remove(position)
                                adapter.notifyItemRangeChanged(position, adapter.getDataList().size - position)
                            }
                        }
                    }

        }
                .register<Int>(R.layout.layout_image_selector_grid_camera) { injector, bean, position ->
                    injector.clicked {
                        val selectedList = localMediaList.map { it.path }
                        (context as Activity).imageSelected(selectedList) { list ->
                            imageSelector.invoke(list)
                            list.forEach { localMedia ->
                                val index = adapter.getDataList().indexOf(localMedia.path)
                                if (index == -1) {
                                    adapter.addData(localMedia.path)
                                }
                            }
                            localMediaList = list
                        }
                    }
                }
                .attachTo(recyclerView)
        adapter.setDataList(list)
    }

    var localMediaList = listOf<LocalMedia>()
}